import os
from CalTorque import CalTorque
from CalTqFixOffset_Gauss import PlotFit_mod
from CalTqFixOffset_PeakFinder import PlotFit_peak
from datetime import datetime 
from string import Template
datapath = 'data/'
lsdir = os.listdir(datapath)
fp = open('stats_fit.csv','w')
fp.write('Date, Direction, MaxTorque (inoz), Final Position (cm)\n')

for f in lsdir:
   if (f.split('.')[-1] not in ['xlsx', 'xls']):
      continue
   data = CalTorque(f)
   if 'in' in data['direction']:
      print f
      PlotFit_mod(data)
      #PlotFit_peak(data)
      if data['direction'] == 'in':
         fp.write(data['run'] + ', ' + data['direction'] + ', ' + str(data['max_torque_inoz']) + ', ' + str(data['final_pos']) + '\n')
      if data['direction'] == 'out':
         fp.write(data['run'] + ', ' + data['direction'] + ', ' + str(data['min_torque_inoz']) + ', ' + str(data['final_pos']) + '\n')

   # Here you should make the plots of all the data

fp.close()

#make the latex document now
lsdir = os.listdir('fitplots/model/')
fp = open('fitplots/model/cal_include_fitplots.tex')
base_str = Template("""
\\begin{figure}
\\caption{$caption}
\\includegraphics[width=0.8\\textwidth]{fitplots/$filename}		
\\end{figure}
""")
lsdir.sort(reverse=True)
file_list = {}
for f in lsdir:
   print f
   run = f.split('_')[0] + f.split('_')[2]
   print run
   if run not in file_list.keys():
      file_list[run[0]] = []
      file_list[run[0]].append(f)
   else:
      file_list[run].append(f)

for run in file_list.keys():
   for f in run:
      s = base_str.substitute(caption = run, filename = f)
      fp.write(s)
   fp.write("\\clearpage")
fp.close()
